package cn.ike.web.controller.cargo;

import cn.ike.domain.cargo.Export;
import cn.ike.domain.cargo.ExportProduct;
import cn.ike.domain.cargo.ExportProductExample;
import cn.ike.service.cargo.ExportProductService;
import cn.ike.service.cargo.ExportService;
import cn.ike.web.controller.BaseController;
import cn.ike.web.utils.BeanMapUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.log4j.Log4j;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Controller
@Log4j
@RequestMapping("/cargo/export")
public class PdfController extends BaseController {

    @Autowired
    private DataSource dataSource;

    @Reference
    private ExportService exportService;

    @Reference
    private ExportProductService exportProductService;

    /**
     * 导出PDF（1） HelloWorld  + 中文字体
     */
    @RequestMapping("/exportPdf1")
    @ResponseBody  // 不进行跳转
    public void exportPdf1() throws JRException, IOException {
        //1. 获取jasper文件流
        InputStream inputStream = request.getSession()
                .getServletContext().getResourceAsStream("/jasper/test01.jasper");

        //2. 创建JasperPrint对象，用于往模板中填充数据
        //参数1：jasper文件流
        //参数2：通过map方式往模板中填充数据
        //参数3：通过数据源的方式往模板中填充数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, new HashMap<>(), new JREmptyDataSource());

        //3. 导出
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

        // 关闭流
        inputStream.close();
    }

    /**
     * 导出PDF（2） 往模板填充数据 A 通过map填充
     * 注意：map的key对应的是模板设置中的Parameter参数名称
     */
    @RequestMapping("/exportPdf2")
    @ResponseBody  // 不进行跳转
    public void exportPdf2() throws Exception {
        InputStream in = request.getSession().getServletContext().getResourceAsStream("/jasper/test02_parameter.jasper");
        Map<String, Object> map = new HashMap<>();
        map.put("userName", "球球");
        map.put("email", "ballball@export.com");
        map.put("companyName", "字节跳动");
        map.put("deptName", "研发部");

        JasperPrint jasperPrint = JasperFillManager.fillReport(in, map, new JREmptyDataSource());

        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

        in.close();

    }

    /**
     * 导出PDF（3） 往模板填充数据 B 数据源填充（1）jdbc数据源
     * 注意：map的key对应的是模板设置中的Parameter参数名称
     */
    @RequestMapping("/exportPdf3")
    @ResponseBody  // 不进行跳转
    public void exportPdf3() throws Exception {
        InputStream inputStream = request.getSession().getServletContext().getResourceAsStream("/jasper/test03_jdbc.jasper");

        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, null, dataSource.getConnection());

        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

        inputStream.close();
    }

    /**
     * 导出PDF（4） 往模板填充数据 B 数据源填充（2）JavaBean数据源
     * 注意：map的key对应的是模板设置中的Parameter参数名称
     */
    @RequestMapping("/exportPdf4")
    @ResponseBody  // 不进行跳转
    public void exportPdf4() throws Exception {
        InputStream in = request.getSession().getServletContext().getResourceAsStream("/jasper/test04_javabean.jasper");

        /**
         * 构造list集合，封装数据
         * 方式1：List<Map<String,Object>>  要求map的key要与模板中Field字段名称一致
         * 方式2：List<User>  要求对象的属性要与模板中Field字段名称一致
         */
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("userName", "球球" + i);
            map.put("email", "ballball@export.com");
            map.put("companyName", "字节跳动");
            map.put("deptName", "研发部" + i);

            list.add(map);
        }
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

        JasperPrint jasperPrint = JasperFillManager.fillReport(in, null, dataSource);

        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

        in.close();
    }

    /**
     * 导出PDF（5） 分组报表，根据企业名称自动进行分组
     */
    @RequestMapping("/exportPdf5")
    @ResponseBody  // 不进行跳转
    public void exportPdf5() throws Exception {
        //1. 获取jasper文件流
        InputStream in = request.getSession().getServletContext().getResourceAsStream("/jasper/test05_group.jasper");

        // 构造list集合，封装数据
        List<Map<String, Object>> list = new ArrayList<>();
        for (int j = 1; j <= 2; j++) {
            for (int i = 0; i < 5; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("userName", "球球" + i);
                map.put("email", "ballball@export.com");
                map.put("companyName", "字节跳动" + j);
                map.put("deptName", "研发部" + i);

                list.add(map);
            }
        }

        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

        JasperPrint jasperPrint = JasperFillManager.fillReport(in, null, dataSource);

        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

        in.close();
    }

    /**
     * 导出PDF（6） 图形报表
     */
    @RequestMapping("/exportPdf6")
    @ResponseBody  // 不进行跳转
    public void exportPdf6() throws Exception {
        //1. 获取jasper文件流
        InputStream in = request.getSession().getServletContext().getResourceAsStream("/jasper/test06_chart.jasper");

        // 构造list集合，封装数据
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            //构造map集合
            Map<String, Object> map = new HashMap<>();
            // 注意：title、value对应的是模板中的Field，且类型也要对应
            map.put("title", "球球" + i);
            map.put("value", new Random().nextInt(100));

            list.add(map);
        }

        // 构造集合对象，用于封装列表数据（对应的是模板中的Field）
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

        JasperPrint jasperPrint = JasperFillManager.fillReport(in, null, dataSource);

        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

        in.close();
    }

    /**
     * 导出PDF, 导出报运详情
     */
    @RequestMapping("/exportPdf")
    @ResponseBody  // 不进行跳转
    public void exportPdf(String id) throws Exception {
        // 获取读取文件流
        InputStream inputStream = request.getSession().getServletContext().getResourceAsStream("/jasper/export.jasper");

        // 查询报运单信息
        Export export = exportService.findById(id);
        // 把对象信息保存到map中
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> exportMap = BeanMapUtils.beanToMap(export);
        list.add(exportMap);

        // 查询报运单商品信息
        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);

        if (exportProductList != null && exportProductList.size() > 0) {
            for (ExportProduct exportProduct : exportProductList) {
                Map<String, Object> productMap = BeanMapUtils.beanToMap(exportProduct);
                list.add(productMap);
            }
        }

        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);

        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, null, dataSource);

        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

        inputStream.close();
    }

}
